package com.gxl.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.gxl.mapper.UsersMapper;
import com.gxl.pojo.UserPageInfo;
import com.gxl.pojo.Users;
import com.gxl.service.UsersService;
import com.gxl.util.MyBatisUtil;

public class UsersServiceImpl implements UsersService {
	@Override
	public List<Users> selAll() throws IOException{
		InputStream resourceAsStream = null;
			resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
		SqlSession openSession = build.openSession();
		List<Users> selectList = openSession.selectList("com.gxl.mapper.UsersMapper.selAll");
		return selectList;
	}

	@Override
	public UserPageInfo showUserList(long pageNumber, int pageSize, String name) {
		UserPageInfo userPageInfo = new UserPageInfo(); 
		
		SqlSession session = MyBatisUtil.getSqlSession();
		UsersMapper mapper = session.getMapper(UsersMapper.class);
		//总记录数
		long selUserCount = mapper.selUserCount(name);
		//计算总页数
		long totalPageNumber = (selUserCount%pageSize == 0)?selUserCount/pageSize:(selUserCount/pageSize + 1);

		
		List<Users> userList = mapper.selUserByPage(pageSize*(pageNumber - 1), pageSize, name);
		
		
		userPageInfo.setTotalCount(selUserCount);
		userPageInfo.setTotalPageNumber(totalPageNumber);
		userPageInfo.setPageNumber(pageNumber);
		userPageInfo.setPageSize(pageSize);
		
		userPageInfo.setName(name);
		userPageInfo.setUserList(userList);
		
		return userPageInfo;
	}

	
}
